package com.neu.dao.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.neu.pojo.Patient;
import com.neu.pojo.RoomRecord;

public class RoomRecordDao {
	File file = new File("roomrecord.json");
	ObjectMapper om = new ObjectMapper();
	
	private static RoomRecordDao recordDao = new RoomRecordDao();
	private RoomRecordDao() {}
	public static RoomRecordDao getInstance() {
		return recordDao;
	}
	
	
	public boolean add(RoomRecord record) {
		ArrayList<RoomRecord> records = new ArrayList<>();
		
		try {
			records = this.om.readValue(file, new TypeReference<List<RoomRecord>>() {});
			for(int i=0;i<records.size();i++) {
				if(records.get(i).getPatient().getId().equals(record.getPatient().getId())) {
					records.get(i).setOverTime(record.getOverTime());
					om.writeValue(file, records);
					return true;
				}
			}
			records.add(record);
			om.writeValue(file, records);
			return true;
		} catch(MismatchedInputException e) {
			records.add(record);
			try {
				om.writeValue(file, records);
			} catch (IOException e1) {
				e1.printStackTrace();
				return true;
			}
			return true;
		}catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean isin(Patient p) {
		ArrayList<RoomRecord> records = new ArrayList<>();
	
		try {
			records = this.om.readValue(file, new TypeReference<List<RoomRecord>>() {});
			for(int i=0;i<records.size();i++) {
				if(records.get(i).getPatient().getId().equals(p.getId())) {
					return true;
				}
			}
			return false;
		} catch(MismatchedInputException e) {
			return false;
		}catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
}
